<template>
<!-- Main content -->
<div>
  <div class="row">
    <div class="col-xs-12">
      <theme-box title="活动查询">
        <form class="form-inline" @submit.prevent v-el:form>
          <form-select title="商户号" :sreach="true" :up-table="true" name="mchtId" :options="branchList" :value.sync="mchtId"></form-select>
          <form-select title="状态" :sreach="true" :up-table="true" name="actStat" :options="actStat"></form-select>
          <!-- <form-select title="类型" :up-table="true" name="actType" :options="actTypes"></form-select> -->
          <form-date-time title="活动开始时间" :up-table="true" name="actBegDate"></form-date-time>
          <form-date-time title="活动结束时间" :up-table="true" name="actEndDate"></form-date-time>
          <span class="pull-right">
            <v-button type="reset" @click="reset" theme="warning" class="pull-right">重置</v-button>
          <v-button theme="primary" @click="search" class="pull-right searchBtn">查询</v-button>
          </span>

        </form>
        <table class="table table-bordered table-striped" style="width:100%;text-align: center;" v-el:table></table>
      </theme-box>
    </div>
    <!-- /.col -->
  </div>
  <edit-model v-ref:edit-model v-if="view==='edit'" :item="item" rule-id='ruleId' :columns-set="columnsSet" @reset-table="reset" @reset-load="resetLoad"></edit-model>
  <trial-model v-ref:trial @reset-table="reset"></trial-model>
  <!-- /.row -->
</div>
<!-- /.content -->
</template>

<style lang="less">
.form-inline .searchBtn {
    margin-right: 10px;
}
</style>

<script>
import TrialModel from './trial'
import EditModel from './edit'
import {
  deepClone
} from 'lib/clone.js'
import {
  dateTransform
} from 'lib/method.js'
import {
  dateTime,
  createDataTable
} from 'ui/collections/general.js'
import serialize from 'form-serialize'
import {dateFormat} from "lib/method.js"

var dataTable;
var columnsSet;
export default {
  components: {
    TrialModel,
    EditModel
  },
  data: () => ({
    view: true,
    mchtId: '',
    mchtIdList: [],
    ruleName: '',
    ruleList: [],
    couponList: [],
    item: {},
    branchList: [],
    columnsSet: [],
    modList: [],
    ruleParams: {},
    actTypes: [{
        key: "所有",
        value: ""
      },
      // {
      //   key: "打折",
      //   value: "00"
      // },
      {
        key: "优惠券",
        value: "01"
      },
      // {
      //   key: "储值卡",
      //   value: "02"
      // },
    ],
    actStat: [{
        key: "所有",
        value: ""
      },
      {
        key: "初始",
        value: "NORMAL"
      },
      {
        key: "暂停",
        value: "RELEASE"
      },
      {
        key: "进行中",
        value: "IN"
      },
      {
        key: "已结束",
        value: "OVER"
      },
    ]
  }),
  methods: {
    publish(data, actStat) {
      this.$post({
        url: "/api/v2" + projectName_Url + "/plat/act/change/" + `${data.actId}`,
        method: "PUT",
        data: {
          actStat: actStat,
          mchtId: data.mchtId
        }
      }).then(res => {
        dataTable.ajax.reload();
      })
    },
    //还原弹出框位置
    resetLoad() {
      this.view = ''
      dataTable.ajax.reload();
    },
    //查询按钮
    search: function() {
      dataTable.ajax.reload();
    },
    //重置按钮
    reset: function() {
      $(".form-inline")[0].reset();
      dataTable.ajax.reload();
    },
    async getBranch() {
      let self = this;
      var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
      let data = await self.$post({
        url: '/api/v2' + projectName_Url + '/list/mcht/' + mchtId,
        method: "GET"
      });
      if (data) {
        let branchList = [{
          value: '',
          key: '所有的商户'
        }];
        let list = data.content.info
        list.forEach(key => {
          let json = {
            value: key.value,
            key: key.key
          };
          branchList.push(json);
        });
        self.$set("branchList", branchList);
      }
    }
  },
  created() {
    let self = this;
    //主页面datatable所用数组
    columnsSet = [{
      title: "商户名称",
      data: "mchtName",
      readonly: true,
      edit: true,
      required: true
    },
    {
      title: "发券数量",
      data: "couponNum",
      readonly: false,
      edit: true,
      required: true
    },
    // {
    //   required: true,
    //   title: "适用商户",
    //   data: "mchtIds",
    //   checkboxOptions: self.mchtIdList,
    //   visible: false
    // },
    {
      required: true,
      title: "活动名称",
      data: "actName",
      edit: true,
      className:'wrap'
    }, {
      required: true,
      title: "活动描述",
      data: "actDsc",
      edit: true,
      className:'wrap'
    }, {
      required: true,
      title: "活动类型",
      data: "actType",
      readonly: true,
      render(data) {
        let obj = self.actTypes.find(item => item.value === data)
        return obj ? obj.key : ''
      },
      options: self.actTypes
    }, {
      required: true,
      title: "活动开始时间",
      data: "actBegDate",
      readonly: true,
      datetime: true,
      render(value) {
        if (value) {
          return dateTransform(value)
        }
      }
    }, {
      required: true,
      title: "活动结束时间",
      data: "actEndDate",
      datetime: true,
      readonly: true,
      render(value) {
        if (value) {
          return dateTransform(value)
        }
      }
    }, {
      required: true,
      title: "活动状态",
      data: "actStat",
      readonly: true,
      render(data) {
        let obj = self.actStat.find(item => item.value === data)
        return obj ? obj.key : ''
      },
      options: self.actStat
    }, {
      required: true,
      title: "活动模板",
      data: "modId",
      visible: false,
      options: self.modList
    }, {
      title: "相关操作",
      className: "operate",
      width: "120px",
      render: function(value, type, row) {
        let btn_groups
        if (row.actStat === 'IN') {
          btn_groups =
            `<button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-warning btn-sm over">结束</button>
                    <button type="button" class="btn btn-primary btn-sm trial">试算</button>
                    <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                  `
        } else if (row.actStat === 'RELEASE') {
          btn_groups =
            `<button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-primary btn-sm publish">发布</button>
                    <button type="button" class="btn btn-primary btn-sm trial">试算</button>
                    <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                  `
        } else {
          btn_groups =
            `<button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-primary btn-sm publish">发布</button>
                    <button type="button" class="btn btn-primary btn-sm trial">试算</button>
                    <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                  `
        }
        return btn_groups
      }
    }]
  },
  ready: async function() {
      // dateTime({
      //   format: "yyyy-mm-dd",
      //   minView: "2",
      //   startDate: "",
      //   endDate: ""
      // })
    this.getBranch();
    this.$set("columnsSet", columnsSet)
    var self = this;
    //创建dataTable
    dataTable = $(this.$els.table).DataTable({
      "columns": this.columnsSet, //定义列
      "ajax": async function(data, callback, settings) {
        var page = [{
          "name": "iDisplayStart",
          "value": 1 + data.start / data.length
        }, {
          "name": "iDisplayLength",
          "value": data.length
        }];
        //表单序列化数据
        var _data = serialize(self.$els.form, {
          hash: true,
          disabled: true,
          empty: true
        });
        _data.aoData = JSON.stringify(page);
        //对交易日期进行数据处理
          _data.actBegDate = _data.actBegDate.replace(/-/g, "");
          _data.actEndDate = _data.actEndDate.replace(/-/g, "");
        //判断日期
          if(_data.actBegDate.length>0 && _data.actEndDate.length>0){
              if(_data.actBegDate-_data.actEndDate > 0){
                  Midway.alert({title: "操作提示", content: '活动开始时间不能大于活动结束时间'})
              }
          }else if(_data.actBegDate.length>0 && _data.actEndDate.length <=0){
              Midway.alert({title: "操作提示", content: '活动结束时间不能为空'})
          }else if(_data.actBegDate.length <= 0 && _data.actEndDate.length > 0){
              Midway.alert({title: "操作提示", content: '活动开始时间不能为空'})
          }
        var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
        //发送请求
        var result = await self.$post({
          url: "/api/v2" + projectName_Url + "/plat/act/query/" + mchtId,
          data: _data
        })
        callback({
          recordsTotal: result.content.total || 0,
          recordsFiltered: result.content.total || 0,
          data: result.content.actList || []
        })
      }
    });

    // 活动发布
    $(self.$el).on("click", ".publish", function() {
      var Row = $(this).closest('tr').get(0);
      const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
      Midway.confirm({
        title: "提示",
        content: `确定要发布活动：${dataArray.actName}?`
      }).then(response => {
        self.publish(dataArray, 'IN')
      }).catch(e => {})
    })
    // 活动结束
    $(self.$el).on("click", ".over", function() {
      var Row = $(this).closest('tr').get(0);
      const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
      Midway.confirm({
        title: "提示",
        content: `确定要结束活动：${dataArray.actName}?`
      }).then(response => {
        self.publish(dataArray, 'OVER')
      }).catch(e => {})
    })

    // 活动试算
    $(self.$el).on("click", ".trial", function() {
      var Row = $(this).closest('tr').get(0);
      const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
      self.$refs.trial.show()
      self.$nextTick(() => {
        self.$refs.trial.modal = {
          actId: dataArray.actId,
          mchtId: dataArray.mchtId,
          chnl_no: 'wechat',
          trading_time: ['00', '00', '00']
        }
      })
    })

    $(self.$el).on("click", ".edit", async function() {
      self.view = ''
      var Row = $(this).closest('tr').get(0);
      const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
      if (dataArray.mchtIds.indexOf(',') !== -1) {
        dataArray.mchtIds = dataArray.mchtIds.split(',')
      } else {
        dataArray.mchtIds = new Array(dataArray.mchtIds)
      }
      self.$set('item', dataArray)

      self.$nextTick(function() {
        self.view = 'edit'
        setTimeout(() => {
          self.$refs.editModel.show();
        },0)
      })
    });

    $(self.$el).on("click", ".delete", async function() {
      var Row = $(this).closest('tr').get(0);
      var dataArray = dataTable.row(Row).data();
      var value = dataTable.row(Row).data().dicValue;
      var id = dataTable.row(Row).data().mchtId;
      await Midway.confirm({
        title: "删除活动",
        content: "是否要删除活动:" + dataArray.actName + "?"
      })
      var result = await self.$post({
        url: "/api/v2" + projectName_Url + "/plat/act/" + `${dataArray.mchtId}/${dataArray.actId}`,
        method: "DELETE"
      });
      dataTable.ajax.reload();
    });

  },
  beforeDestroy() {
    $(this.$el).off("click")
  }
}
</script>
